package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.PageUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.FocusApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.dubbo.api.VideoShowApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.enums.VideoType;
import com.tanhua.model.mongo.Focus;
import com.tanhua.model.mongo.Video;
import com.tanhua.model.mongo.VideoShow;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.VideoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SmallVideosService {

    @Autowired
    private FastFileStorageClient client;

    @Autowired
    private FdfsWebServer webServer;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoShowApi videoShowApi;

    @DubboReference
    private FocusApi focusApi;


    /**
     * 上传视频
     *
     * @param videoThumbnail 封面图片文件
     * @param videoFile      视频文件
     */
    public void saveVideos(MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {

        if (videoFile.isEmpty() || videoThumbnail.isEmpty()) {
            throw new BusinessException(ErrorResult.error());
        }

        //1、将视频上传到FastDFS,获取访问URL
        String filename = videoFile.getOriginalFilename();  // abc.mp4
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
        //2、将封面图片上传到阿里云OSS，获取访问的URL
        String imageUrl = ossTemplate.upload(videoThumbnail.getOriginalFilename(), videoThumbnail.getInputStream());
        //3、构建Videos对象
        Video video = new Video();
        video.setUserId(UserHolder.getUserId());
        video.setPicUrl(imageUrl);
        video.setVideoUrl(videoUrl);
        video.setText("我就是我，不一样的烟火");
        //4、调用API保存数据
        String videoId = videoApi.save(video);
        if (StringUtils.isEmpty(videoId)) {
            throw new BusinessException(ErrorResult.error());
        }

        //发送消息
        mqMessageService.sendLogMessage(UserHolder.getUserId(), "0301", "video", videoId);
    }

    //查询视频列表
    @Cacheable(
            value = "videos",
            key = "T(com.tanhua.server.interceptor.UserHolder).getUserId()+'_'+#page+'_'+#pagesize")
    //userid _ page_pagesize
    public PageResult queryVideoList(Integer page, Integer pagesize) {

        //1、查询redis数据
        String redisKey = Constants.VIDEOS_RECOMMEND + UserHolder.getUserId();
        String redisValue = redisTemplate.opsForValue().get(redisKey);
        //2、判断redis数据是否存在，判断redis中数据是否满足本次分页条数
        List<Video> list = new ArrayList<>();
        int redisPages = 0;
        if (!StringUtils.isEmpty(redisValue)) {
            //3、如果redis数据存在，根据VID查询数据
            String[] values = redisValue.split(",");
            //判断当前页的起始条数是否小于数组总数
            if ((page - 1) * pagesize < values.length) {
                List<Long> vids = Arrays.stream(values).skip((page - 1) * pagesize).limit(pagesize)
                        .map(e -> Long.valueOf(e))
                        .collect(Collectors.toList());
                //5、调用API根据PID数组查询动态数据
                list = videoApi.findMovementsByVids(vids);
            }
            redisPages = PageUtil.totalPage(values.length, pagesize);
        }
        //4、如果redis数据不存在，分页查询视频数据
        if (list.isEmpty()) {
            //page的计算规则，  传入的页码  -- redis查询的总页数
            list = videoApi.queryVideoList(page - redisPages, pagesize);  //page=1 ?
        }
        //5、提取视频列表中所有的用户id
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        // 根据用户id查询视频id
        List<Video> videoIds = videoApi.findVidesIds(userIds);
        //6、查询用户信息
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //7、构建返回值
        List<VideoVo> vos = new ArrayList<>();
        for (Video video : list) {
            UserInfo info = map.get(video.getUserId());
            if (info != null) {
                VideoVo vo = VideoVo.init(info, video);
                // 设置是否点赞
                String value = (String) redisTemplate.opsForHash().get(Constants.MOVEMENTS_INTERACT_KEY + video.getId(), Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId());
                if(video.getUserId() == vo.getUserId() && "1".equals(value)){
                    vo.setHasLiked(1);
                }
                // 设置是否关注
                String isFocus = (String) redisTemplate.opsForHash().get(Constants.FOCUS_USER_KEY + video.getUserId(),Constants.FOCUS_USER_KEY + UserHolder.getUserId());
                if(video.getUserId() == vo.getUserId() && "1".equals(isFocus)){
                    vo.setHasFocus(1);
                }
                vos.add(vo);
            }
        }

        return new PageResult(page, pagesize, 0l, vos);
    }


    // 分页查询视频评论列表
    public PageResult findVideos(String videoId, Integer page, Integer pagesize) {

        //1、调用API查询评论列表
        List<VideoShow> list = videoApi.findVideos(videoId, VideoType.COMMENT.getType(), page, pagesize);
        //2、判断list集合是否存在
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //3、提取所有的用户id,调用UserInfoAPI查询用户详情
        List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        //4、构造vo对象
        List<VideoVo> vos = new ArrayList<>();
        for (VideoShow videoShow : list) {
            UserInfo userInfo = map.get(videoShow.getUserId());
            if (userInfo != null) {
                Video video = new Video();
                BeanUtils.copyProperties(videoShow, video);
                VideoVo vo = VideoVo.init(userInfo, video);
                // 设置内容
                vo.setContent(videoShow.getContent());
                // 判断是否点赞
                String value = (String) redisTemplate.opsForHash().get(Constants.MOVEMENTS_INTERACT_KEY + videoShow.getId(), Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId());
                if("1".equals(value)){
                    vo.setHasLiked(1);
                }
                vos.add(vo);
            }
        }
        //5、构造返回值
        return new PageResult(page, pagesize, 0l, vos);
    }

    // 视频发布评论
    public void saveComments(String videoId, String comment) {
        //1、获取操作用户id
        Long userId = UserHolder.getUserId();
        // 不可输入空字符串
        if (StringUtils.isEmpty(comment)) {
            throw new BusinessException(ErrorResult.nullComment());
        }
        //2、构造Video
        VideoShow videoShow = new VideoShow();
        videoShow.setVideoId(new ObjectId(videoId));
        videoShow.setVideoType(VideoType.COMMENT.getType());
        videoShow.setContent(comment);
        videoShow.setUserId(userId);
        videoShow.setCreated(System.currentTimeMillis());
        //3、调用API保存评论
        videoShowApi.saveViodeLike(videoShow);

    }

    // 视频点赞
    public Integer videoLikeById(String videoId) {

        // 调用api查询当前用户是否点赞
        Boolean vsIsExist = videoShowApi.findVideoShow(videoId, UserHolder.getUserId(), 1);
        if(vsIsExist){
            throw new BusinessException(ErrorResult.likeError());
        }
        //1、调用API保存数据到Mongodb
        VideoShow videoShow = new VideoShow();
        videoShow.setVideoId(new ObjectId(videoId));
        videoShow.setVideoType(CommentType.LIKE.getType());
        videoShow.setUserId(UserHolder.getUserId());
        videoShow.setCreated(System.currentTimeMillis());
        Integer count = videoShowApi.saveViodeLike(videoShow);
        //2、拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
        return count;
    }

    // 对视频取消点赞
    public Integer dislikeVideo(String videoId) {

        Boolean vsIsExist = videoShowApi.findVideoShow(videoId, UserHolder.getUserId(), 1);
        if(!vsIsExist){
            throw new BusinessException(ErrorResult.disLikeError());
        }

        //1、调用API，删除数据，返回点赞数量
        VideoShow videoShow = new VideoShow();
        videoShow.setVideoId(new ObjectId(videoId));
        videoShow.setVideoType(VideoType.LIKE.getType());
        videoShow.setUserId(UserHolder.getUserId());
        Integer count = videoShowApi.delete(videoShow);
        //2、拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
        return count;
    }

    // 视频评论点赞
    public void likeComment(String videoShowId) {
        // 调用API查询用户是否已点赞
       //  Boolean hasComment = videoShowApi.hasVideoShow(videoShowId, UserHolder.getUserId(), VideoType.LIKE);
        // 调用API保存数据到Mongodb
        VideoShow videoShow = new VideoShow();
        videoShow.setVideoId(new ObjectId(videoShowId));
        videoShow.setVideoType(CommentType.LIKE.getType());
        videoShow.setUserId(UserHolder.getUserId());
        videoShow.setLikeCount(1);
        videoShow.setCreated(System.currentTimeMillis());
        videoShowApi.saveComment(videoShow);
        // 拼接redis的key，将用户的点赞状态存入redis
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoShowId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");
    }


    // 视频评论取消点赞
    public void dislikeComment(String videoShowId) {
        // 调用api查询点赞数据
        // VideoShow videoApi = videoShowApi.findVideo(videoShowId, VideoType.LIKE.getType());
        VideoShow videoApi = videoShowApi.findVideo(videoShowId, UserHolder.getUserId());
        if(videoApi == null){
            throw new BusinessException(ErrorResult.disLikeError());
        }
        // 调用API，删除数据
        videoShowApi.deleteVideoShow(videoApi);
        // 拼接redis的key，删除点赞状态
        String key = Constants.MOVEMENTS_INTERACT_KEY + videoShowId;
        String hashKey = Constants.MOVEMENT_LIKE_HASHKEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    // 关注成功，记录粉丝关系到mongodb
    public Boolean userFocus(Long userFocusId) {
        Long userId = UserHolder.getUserId();
        focusApi.save(userId, userFocusId);

        // 根据被关注人id 查询关注数
        Video video = videoApi.findVideo(userFocusId);
        Integer loveCount = video.getLoveCount() + 1;
        videoApi.updateVideo(userFocusId, loveCount);

        // 将关注关系保存在redis
        String key = Constants.FOCUS_USER_KEY + userFocusId;
        String hashKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        redisTemplate.opsForHash().put(key, hashKey, "1");

        return true;
    }

    // 取消关注
    public void userUnFocus(Long userUnFocusId) {
        Focus focus = focusApi.findFocus(UserHolder.getUserId(), userUnFocusId);
        if(focus == null){
            throw new BusinessException(ErrorResult.error());
        }
        focusApi.delete(focus);

        // 根据被关注人id 查询关注数
        Video video = videoApi.findVideo(userUnFocusId);
        Integer loveCount = video.getLoveCount() - 1;
        videoApi.updateVideo(userUnFocusId, loveCount);

        // 将关注关系保存在redis
        String key = Constants.FOCUS_USER_KEY + userUnFocusId;
        String hashKey = Constants.FOCUS_USER_KEY + UserHolder.getUserId();
        redisTemplate.opsForHash().delete(key, hashKey);

    }
}
